﻿#include "libcomm.h"

CommLibrary::CommLibrary(const char* szLibraryPath)
	:hlib(NULL)
{
	if (NULL == OpenLibrary(szLibraryPath))
	{
#ifdef COMM_MSVC
		LOGDEBUG("load library \"%s\" failure: %s.\n", szLibraryPath, MYLIB_STRERROR(MYLIB_ERRNO));
#else
		LOGDEBUG("load library \"%s\" failure: %s.\n", szLibraryPath, dlerror());
#endif
	}
}

CommLibrary::~CommLibrary()
{
	CloseLibrary();
}

bool CommLibrary::IsValid() { return (NULL != hlib); }

void* CommLibrary::GetProcAddress(const char* funcname)
{
	void* func = NULL;
#ifdef COMM_MSVC
	func = ::GetProcAddress(hlib, funcname);
#else
	func = dlsym(hlib, funcname);
#endif
	return func;
}


HMODULE CommLibrary::OpenLibrary(const char* libPath)
{
#ifdef COMM_MSVC
	hlib = LoadLibraryExA(libPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
#else
	hlib = dlopen(libPath, RTLD_LAZY);
#endif
	return hlib;
}

void CommLibrary::CloseLibrary()
{
	if (NULL != hlib)
	{
#ifdef COMM_MSVC
		FreeLibrary(hlib);
#else
		dlclose(hlib);
#endif
		hlib = NULL;
	}
}

